import 'dart:convert';
import 'package:pacsun/constants/apiConstants.dart';
import 'package:pacsun/model/apiResponse.dart';
import 'package:logger/logger.dart';
import 'base/apiClient.dart';

var log = Logger();

// ------------------------------------------------------------------------------------- //
class TaskApi {
  final ApiClient _apiClient = ApiClient();

  Future<Map<String, dynamic>?> getTasks(
    Map<String, dynamic> request,
  ) async {
    request.remove('aid');
    final String uri = '/api/v1/task/config/pageActive';
    final response = await _apiClient.post(uri,
        data: jsonEncode(request), headers: ApiConstants.jsonHeaders);
    log.w('$uri---->${response.requestOptions.data.toString()}');

    log.w('$uri\n>>>${response.data['data']['total']}');
    return {
      'list':
          List<Map<String, dynamic>>.from(response.data['data']['data'] ?? []),
      'total': response.data['data']['total'] ?? 0,
      'tabCurrent': request['tabCurrent']
    };
  }

  Future<Map<String, dynamic>?> getMyTasks(Map<String, dynamic> request) async {
    final String uri = '/api/v1/task/record/getByAid';
    final response = await _apiClient.post(uri,
        data: jsonEncode(request), headers: ApiConstants.jsonHeaders);

    return {
      'list':
          List<Map<String, dynamic>>.from(response.data['data']['data'] ?? []),
      'total': response.data['data']['total'] ?? 0,
      'tabCurrent': request['tabCurrent']
    };
  }

  Future<Map<String, dynamic>?> getTaskDetail(String id) async {
    final String uri = '/api/v1/task/config/';
    final response =
        await _apiClient.get(uri + id, headers: ApiConstants.jsonHeaders);
    return {'data': response.data['data']};
  }

  Future<Map<String, dynamic>?> getMyTaskDetail(String id) async {
    final String uri = '/api/v1/task/record/get/';
    final response =
        await _apiClient.get(uri + id, headers: ApiConstants.jsonHeaders);
    return {'data': response.data['data']};
  }

  Future<Map<String, dynamic>?> taskSaveUpload(
      Map<String, dynamic> data) async {
    final String uri = '/api/v1/task/report/save';
    final response = await _apiClient.post(uri,
        headers: ApiConstants.jsonHeaders, data: data);
    final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
      response.data,
      (data) => data as Map<String, dynamic>,
    );
    if (apiResponse.success) {
      return {'data': apiResponse.data};
    } else {
      throw Exception('发布内容失败: ${apiResponse.message}');
    }
  }
}
